package com.legna.xyq.alert.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Robot;
import java.awt.Rectangle;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class ColorDetectionService {

    private Boolean switchOpen = true;
    private Boolean isSend = true;

    private List<String> receiveEmails = new ArrayList<>();

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    @Autowired
    private EmailService emailService;

    @Scheduled(cron = "0/1 * * * * ? ")
    public void getMessage() throws InterruptedException {
        if (switchOpen){
            Thread.sleep(new Random().nextInt(500));
            checkColor();
        }
    }

    @Scheduled(cron = "0 0/1 * * * ? ")
    public void openSend(){
        if (switchOpen){
            isSend = true;
        }
    }
    public Boolean switchSendFun(){
        switchOpen = !switchOpen;
        return switchOpen;
    }

    public void checkColor() {
        try {
            Rectangle rectangle = new Rectangle(0, 0, 1920, 1080);

            Robot robot = new Robot();

            Color color = robot.getPixelColor(396, 1047);

            if (judgeColor(color)) {
                System.out.println(sdf.format(new Date())+":你有新的系统消息");
                sendMessage();
            }

        } catch (AWTException e) {
            e.printStackTrace();
        }
    }

    private boolean judgeColor(Color color) {
        int red = color.getRed();
        int green = color.getGreen();
        int blue = color.getBlue();
        return red >= 157 && red <= 177 && green >= 86 && green <= 106 && blue >= 34 && blue <= 54;
    }


    public List<String> addReceiver(String addEmail){
        receiveEmails.add(addEmail);
        return receiveEmails;
    }

    public List<String> removeReceiver(String removeEmail){
        receiveEmails.removeIf(next -> next.equals(removeEmail));
        return receiveEmails;
    }

    public void sendMessage(){
        if (isSend){
            emailService.sendEmail("15067388403@163.com","15067388403@163.com","你有新的系统消息","你有新的系统消息,如果聊天请忽略");
            for (String receiveEmail : receiveEmails) {
                try {
                    emailService.sendEmail("15067388403@163.com",receiveEmail,"你有新的系统消息","你有新的系统消息,如果聊天请忽略");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            isSend = false;
        }
    }
}

